package com.agileai.portal.controller.sso;

import java.util.List;

import javax.servlet.http.HttpSession;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.sso.SSOPrincipal;
import com.agileai.portal.bizmoduler.sso.SSOTicket;
import com.agileai.portal.bizmoduler.sso.UserSSOService;

public class SSORedirectHandler extends BaseHandler{
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String ticketId = param.get("ticketId");
		UserSSOService userSSOService = this.lookupService(UserSSOService.class);
		
		HttpSession httpSession = this.getRequest().getSession();
		SSOPrincipal principal = (SSOPrincipal)httpSession.getAttribute(SSOPrincipal.class.getName());
		String userId = principal.getUserId();
		List<DataRow> records = userSSOService.findEditApplications(userId);
		this.setAttribute("userId", userId);
		if (isValidTicketId(records, ticketId)){
			SSOTicket ssoTicket = userSSOService.findSSOTicket(ticketId);
			SSOTicket.evalSSOTicket(ssoTicket,principal.getUserId());
			this.setAttribute("ssoTicket", ssoTicket);			
		}
		return new LocalRenderer(getPage());
	}
	
	private boolean isValidTicketId(List<DataRow> records,String ticketId){
		boolean result = false;
		for (int i=0;i < records.size();i++){
			DataRow row = records.get(i);
			String tempTicketId = row.stringValue("TICKET_ID");
			if (tempTicketId.equals(ticketId)){
				result = true;
				break;
			}
		}
		return result;
	}
}